﻿using System;
using System.Text.RegularExpressions;
using NHibernate.Validator.Engine;

namespace NHibernate.Sidekick.Utils.Validations
{
    /// <summary>
    /// Validates the <see cref="PhoneAttribute"/> rules.
    /// </summary>
    public class PhoneValidator : IInitializableValidator<PhoneAttribute>
    {
        private Regex _regex;

        /// <summary>
        /// Takes the attribute values and initializes the <see cref="IValidator"/>.
        /// </summary>
        /// <param name="parameters">parameters</param>
        public void Initialize(PhoneAttribute parameters)
        {
            _regex = new Regex(@"^[2-9]\d{2}-\d{3}-\d{4}$");
        }

        /// <summary>
        /// Determines if the object passes validator's constraints.
        /// </summary>
        /// <param name="value">Object to be validated.</param>
        /// <param name="constraintValidatorContext">Context for the validator constraint.</param>
        public bool IsValid(object value, IConstraintValidatorContext constraintValidatorContext)
        {
            return value == null || _regex.IsMatch(value.ToString());
        }
    }

    /// <summary>
    /// Ensures the string is a a well-formed email phone number.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
    [ValidatorClass(typeof(PhoneValidator))]
    public class PhoneAttribute : Attribute, IRuleArgs
    {
        private string message = "not a well-formed phone number";
        /// <summary>
        /// The displayed error message.
        /// </summary>
        /// <value></value>
        public string Message
        {
            get { return message; }
            set { message = value; }
        }
    }
}
